/*
 * OpenParts
 * A dynamic-loading components framework for GWT
 * Copyright (C) 2011 Christophe Bouthier  [chris{AT}binary-gastronome{DOT}fr]
 *
 * This work is partially based on work I have done at INRIA (http://www.inria.fr) 
 * in the context of the Qualipso European Project (http://qualipso.org/),
 * The work done at INRIA is Copyright (C) 2006-2011 INRIA
 *
 * This work is distributed under the LGPL version 3
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version 3
 * as published by the Free Software Foundation. See the GNU
 * Lesser General Public License in LGPL.txt for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package fr.openparts.OpenParts.client;

import java.util.Arrays;


import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArrayString;

import fr.openparts.OpenParts.logging.client.OPLogger;
import fr.openparts.OpenParts.logging.client.OPLogging;

/**
 * The OPBindingAction class is a binding object representing a binded action, containing slot id and view factory. OPBindingAction is a JavaScriptObject, that
 * is a real javascript object mapped to Java thanks to GWT overlay absolutely fantastic technique.
 * 
 * @author Christophe Bouthier [chris{AT}binary-gastronome{DOT}fr]
 * @creation.date 31 December 2009
 */
public final class OPBindingAction extends JavaScriptObject {

    protected static final OPLogger logger = OPLogging.getLoggerForDomain("viewDisplay");

    /**
     * Create and return a new OPBindingAction object without any mandatory parameters.
     * 
     * @param actionName
     *            the name of the action to bind. Shouldn't be null.
     * @return the corresponding OPBindingAction. Cannot be null.
     */
    public final static OPBindingAction actionFactory(final String actionName) {
        return actionFactory(actionName, null);
    }

    /**
     * Create and return a new OPBindingAction object. Take in parameter the name of the action and its mandatory parameters.
     * 
     * @param actionName
     *            the name of the action to bind. Shouldn't be null.
     * @param mandatoryParams
     *            the name of its mandatory parameters. Can be empty, can be null.
     * @return the corresponding OPBindingAction. Cannot be null.
     */
    public final static OPBindingAction actionFactory(final String actionName, final String[] mandatoryParams) {
        assert actionName != null : "parameter actionName shouldn't be null";

        final OPBindingAction action = actionFactoryImpl(actionName);
        if (mandatoryParams != null) {
            final JsArrayString params = action.getJsMandatoryParamsNames();
            for (int i = 0; i < mandatoryParams.length; i++) {
                params.set(i, mandatoryParams[i]);
            }
        }
        return action;
    };

    /**
     * Real implementation of creating and returning a new OPBindingAction object.
     * 
     * @param actionName
     *            the name of the action to bind.
     * @return the corresponding OPBindingAction.
     */
    private final static native OPBindingAction actionFactoryImpl(final String actionName) /*-{
        var action = {};
        action.name = actionName;
        action.mandatoryParams = new Array();
        action.displayView = null;
        return action;
    }-*/;

    /**
     * Protected constructor, necessary because it's a JavaScriptObject.
     */
    protected OPBindingAction() {}

    /**
     * Return the name of the action represented by this binding object.
     * 
     * @return the name of the action represented by this binding object. Cannot be null.
     */
    public final native String getActionName() /*-{
        return this.name;
    }-*/;

    /**
     * Returns an array of names of mandatory parameters for the view represented by this binding object.
     * 
     * @return an array of names of mandatory parameters for this action. Can be empty, cannot be null.
     */
    public final String[] getMandatoryParamsNames() {
        final JsArrayString mandatoryParams = getJsMandatoryParamsNames();
        String[] result = new String[mandatoryParams.length()];
        for (int i = 0; i < mandatoryParams.length(); i++) {
            result[i] = mandatoryParams.get(i);
        }
        return result;
    }

    /**
     * Returns the Js array of mandatory parameters for the view represented by this binding object.
     * 
     * @return the direct Js array of mandatory parameters for this action. Can be empty, cannot be null.
     */
    private final native JsArrayString getJsMandatoryParamsNames() /*-{
        return this.mandatoryParams;
    }-*/;

    /**
     * Call the display view callback that will display the view corresponding to this action. Pass as parameter the slot id to use to display the view, and the
     * params for the view. Don't do anything if there is no display view callback binded.
     * 
     * Check that the params contains the mandatory params. If not, return the name of the missing param;
     * 
     * @param slotId
     *            the slot id to use. Shouldn't be null.
     * @param params
     *            the params to pass to the view. Can be null.
     * @return the name of the missing param if the view needs mandatory params and that the given params don't contains all the necessary mandatory params,
     *         null otherwise.
     */
    public final String displayView(final String slotId, final OPParamsJS params) {
        assert slotId != null : "parameter slotId shouldn't be null";
        logger.log("Trying to display view of action " + getActionName() + " in slot " + slotId + (params == null ? " with no params" : " with params " + params.getDescription()));
        logger.log("Action " + getActionName() + 
                (getMandatoryParamsNames().length == 0 ? " with no mandatory params" : " with mandatory params " + Arrays.toString(getMandatoryParamsNames())));
        
        final String missingMandatory = checkMandatoryParams(params);
        if (missingMandatory != null) {
            logger.log("Cannot display view, mandatory param " + missingMandatory + " is missing");
            return missingMandatory;
        }

        logger.log("Displaying view in slot " + slotId + (params == null ? " with no params" : " with params " + params.getDescription()));
        displayViewImpl(slotId, params);

        return null;
    }

    /**
     * Real implementation of calling the display view callback. Pass as parameter the slot id to use to display the view, and the params for the view. Don't do
     * anything if there is no display view callback binded.
     * 
     * @param slotId
     *            the slot id to use.
     * @param params
     *            the params to pass to the view.
     */
    private final native void displayViewImpl(final String slotId, final OPParamsJS params) /*-{
        if (this.displayView != null) {
            this.displayView(slotId, params);
        }
    }-*/;

    /**
     * Check that the params contains the mandatory params. If not, return the name of the missing param;.
     * 
     * @param params
     *            the set of params to tests.
     * @return the name of the missing param if the given params don't contains all the necessary mandatory params, null otherwise.
     */
    private final String checkMandatoryParams(OPParamsJS params) {
        final JsArrayString mandatoryParams = getJsMandatoryParamsNames();
        for (int i = 0; i < mandatoryParams.length(); i++) {
            if ((params == null) || (params.getParamValue(mandatoryParams.get(i)) == null)) {
                return mandatoryParams.get(i);
            }
        }
        return null;
    }

}
